<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\shop\controller;
use think\Controller;
use think\Db;

class  Base extends Controller {
    protected $_error;
    protected $_header;//用户的请求头信息
    protected $config = array(
        'partner'=>'2088621781822784',//用不着
        'seller_id'=>'admin@bagepanzi.com',//用不着
        'sign_type'=>'RSA2',// 直接写死了
        'it_b_pay'=>'10m',//用不着
        'md5'=>'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        'ali_public'=>'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl52A0hQejykjLpsxv5Bp4pHlri3GFYdzHtHpk33yKZKuFglgwVm/xTxur+6wKKYssyBfBXwP7vibn+JNw/yg0WuYYpv41PIUmwIz4BMjPCb+0Yqnn+Zuk+hoJQtcXdj+q4lEvvbOvTKm7aHVE2TdL62kXB6WVvc1Tk2jSFg1yO7ljvsbZuFq+b24VyOR6h8cXyUBpeoptlmpVk/Q3rbDltuE+PinOXgVQVKkjKBrKx9j1tl8MZrMOsCEgxYNNmi0ycJqfa3NSPunYsocld/xo39OVAZ7ophZi3dwpBIHOmqHbI+6hf90H/FHcMhERL5OnURX/t+GX4+LOl1/R0U6uQIDAQAB',
        'public_key'=>"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2b4GAsKv3MXAgKvPAVHJeT0MZ+XX5Ke55q74ecV/Wy9NN7wmJBUEVqf/jZEaCtxEhNUNjz74XyoTN/xvYeZ2sjtMSmCzjAuvUUM5GlAMvwg+UpIWC95J1Sz3eLOfzciPUhcd2A4yCEHXjjlgOfWB25U8HBYr8kddfHGm5sKC3IiGM88GLu4CM9MSjdDtvMOeQOh4Zptq9Gz5FVA1BO1nvd4Eb3iUyy3xeVWrYRd1NkSdHJ+TGqEOGIa9X4qtZPcwK5T9Q0I1b7QYt1JuV0j5iizDqP79qMHhX/Hmw+abmJAKM7wfNdS85NXQh+Lkdi7X0qvCzUT7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ehMypPcxotn4vGB9b/lWVvfA4dpGTSKwtL3TAoGBANSx5ZpJipdzpejFL/vVJBgBNNutSmz1Hvd0bNX59lVzoxLjb+ZGtyjE+4m5o21H3QCxBfrU4HR5s/sNoeGGQe82wIgYRiGqPlnS4f6yuwpfnp0bZ5JRVxbyZZOh1qXTWfejga1KtkSPHbTatsZE97HmnmBxajQUWDbnvlG9jJgTAoGBAJhTa79nXOuX8IerBBFSjz1DxTOmsIGWs5tIWQah1DwfmqB/9QZQY2xj7omcIlD990azQ6Kg1wryFU+Q1bh99PCobTT+FDIq7zrCDXQgK3t8mPWiirXVT4T1gSx76/pIN4mFlPFC9OxaXc3KLPj7bP+Omf2z1rbaKh6qlP+4ZZ7tAoGASU7kUHm/o35qU8Sy9f0YSeOq4JRMast8tyj7hqI5ZEb4LCHioFpK76qmUHrsgAXO48NeQ0AZPsNA7jqYVEPHemcpk+Qzva0VkinUhSb+Hvqeam314lQpg0ctpJf73yjIy9ScxCFxNnoDLybWnbptazW3OwhKNdyVQ675kp/GXVU='
    );
    // 定义配置项
    private $config2=array(
        'APPID'              => 'wx8ab4cc1831384ba3', // 微信支付APPID.
        'MCHID'              => '1515746111', // 微信支付MCHID 商户收款账号
        'KEY'                => '2XWCaOA2m2u1Se2SrMjeNvXSSUcZjMkN', // 微信支付KEY
        'APPSECRET'          => '579a1c4bb07f4f1c08a7f9e109629aa5', // 公众帐号secert (公众号支付专用)
        'NOTIFY_URL'         => 'http://mww5.xuanwumobile.com/shop/Index/huidiaoWx', // 接收支付状态的连接

    );
    public function __construct()
    {

//        parent::__construct();

    }

    /**
     * 验证唯一——单点登录
     * user_id，time，salt，value
     * @return string
     */
    public  function checkAll($uid,$time,$value,$reqKey){//$uid,$time,$value
        header("Access-Control-Allow-Origin:*");
//        return true;
        $today = date('Y-m-d');
        $insert = Db::table('up_goods')
            ->where('g_kill_end','<',$today)
            ->where('g_prcie_kill','>',0)
            ->where('g_status',1)
            ->field('g_name,g_id,g_price_before,g_price_now,g_prcie_kill,g_kill_end,g_kill_start,g_time')
            ->select();
        if($insert){
            Db::table('up_goods_kill')->insertAll($insert);
            Db::table('up_goods')
                ->where('g_kill_end','<',$today)
                ->where('g_prcie_kill','>',0)
                ->where('g_status',1)
                ->update(['g_prcie_kill'=>0]);
        }
        if($uid == 0){
            return true;
        }else{
            $user = Db::table('up_shops')->where('s_id',$uid)->find();
            if($user['s_join_end'] < date('Y-m-d')){
                return false;
            }
            if($user['s_admin'] != 1){
                return false;
            }
            $token = $user['s_token'];
            $appId = "A6070308312682";
            $appkey = "9AF807B0-BE12-F521-6998-6D57B0CCE8BB";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey){
                return false;
            }else{
                return true;
            }
        }
    }
    /**
     * 配送员：验证唯一——单点登录
     * user_id，time，salt，value
     * @return string
     */
    public  function checkAllDriver($uid,$time,$value,$reqKey){//$uid,$time,$value
        header("Access-Control-Allow-Origin:*");
        if($uid == 0){
            return true;
        }else{
            $user = Db::table('up_shop_driver')->where('d_id',$uid)->find();
            $token = $user['d_token'];
            $appId = "A6070308312682";
            $appkey = "9AF807B0-BE12-F521-6998-6D57B0CCE8BB";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey){
                return false;
            }else{
                return true;
            }
        }
    }

    public  function killUpdate(){//$uid,$time,$value
        $today = date('Y-m-d');
        Db::table('up_goods')
            ->where('g_kill_end','<',$today)
            ->where('g_prcie_kill','>',0)
            ->where('g_status',1)
            ->update(['g_prcie_kill'=>0]);
    }

    /**
     * 云之讯发送短信
     * @param $phone
     * @param $num
     * @return mixed
     */
    public function duaxin($phone,$num){
        $body_json = array(
            'sid'=>'2b6e76df39bef2e4a99eee7b77225c91',
            'token'=>'26a41e1a5b90f6a0bd2e4fb4fb6a713e',
            'appid'=>'760e6b2f0a45439585835cbed2e12e18',
            'templateid'=>'373248',
            'param'=>$num,
            'mobile'=>$phone,
            'uid'=>'',
        );
        $body = json_encode($body_json);
        $header = array(
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
        );
        $url = 'https://open.ucpaas.com/ol/sms/sendsms';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
    }
    public function uuid($prefix = '')
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid  = substr($chars,0,8);
        $uuid .= substr($chars,8,4);
        $uuid .= substr($chars,12,4);
        $uuid .= substr($chars,16,4);
        $uuid .= substr($chars,20,12);
        return $prefix . $uuid;
    }

    /** 敏感词过滤
     * @param string $prefix
     * @return string
     */
    public function fuckWord($fuck)
    {
        $hei = Db::table('up_words')->column('w_name');
        if($hei){
            $blacklist="/".implode("|",$hei)."/i";
            if(preg_match($blacklist, $fuck, $matches)){
                return true;
            } else {
                return false;
            }
        }else{
            return false;
        }
    }
    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no,$money){
        require_once '/data/wwwroot/mww5.xuanwumobile.com/extend/aliqrcode/f2fpay/model/builder/AlipayTradePrecreateContentBuilder.php';
        require_once '/data/wwwroot/mww5.xuanwumobile.com/extend/aliqrcode/f2fpay/service/AlipayTradeService.php';
        $outTradeNo = $no;
        // (必填) 订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店当面付扫码消费”
        $subject = '商户入驻';
        // (必填) 订单总金额，单位为元，不能超过1亿元
        // 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
        $totalAmount = $money;
        // 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品2件共15.00元"
        $body = "商户入驻费用";
        // 支付超时，线下扫码交易定义为5分钟
        $timeExpress = "5m";
        // 创建请求builder，设置请求参数
        $qrPayRequestBuilder = new \AlipayTradePrecreateContentBuilder();
        $qrPayRequestBuilder->setOutTradeNo($outTradeNo);
        $qrPayRequestBuilder->setTotalAmount($totalAmount);
        $qrPayRequestBuilder->setTimeExpress($timeExpress);
        $qrPayRequestBuilder->setSubject($subject);
        $qrPayRequestBuilder->setBody($body);
        // 调用qrPay方法获取当面付应答
        $alipay_config = array(
            'gatewayUrl'=>'https://openapi.alipay.com/gateway.do',//用不着
            'app_id'=>'2018090761306686',//用不着
            'sign_type'=>'RSA2',// 直接写死了
            'merchant_private_key'=>'MIIEpQIBAAKCAQEA2b4GAsKv3MXAgKvPAVHJeT0MZ+XX5Ke55q74ecV/Wy9NN7wmJBUEVqf/jZEaCtxEhNUNjz74XyoTN/xvYeZ2sjtMSmCzjAuvUUM5GlAMvwg+UpIWC95J1Sz3eLOfzciPUhcd2A4yCEHXjjlgOfWB25U8HBYr8kddfHGm5sKC3IiGM88GLu4CM9MSjdDtvMOeQOh4Zptq9Gz5FVA1BO1nvd4Eb3iUyy3xeVWrYRd1NkSdHJ+TGqEOGIa9X4qtZPcwK5T9Q0I1b7QYt1JuV0j5iizDqP79qMHhX/Hmw+abmJAKM7wfNdS85NXQh+Lkdi7X0qvCzUT7pUsded6YtKYpCQIDAQABAoIBAQDKjwr6cHC3mcN+L9Zv7MzXm2I6GUihLyMypZ0DcyYKBtP3wHFe6apSjxCeetjWN5kKVUS6+KKHrRWZ5J0dXw8WuTE8k/8Tjh83IqkxgDyLTjjkCYC248Cdrqo9QCSuhCBIBrc9sd77bX0AkwGgiXKXepojqsCRL7CZPwU78MFaM3QVUimLYASE9Q6/Z3jhbEUuSK7uU96vOD+mfYVCMt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hQejykjLpsxv5Bp4pHlri3GFYdzHtHpk33yKZKuFglgwVm/xTxur+6wKKYssyBfBXwP7vibn+JNw/yg0WuYYpv41PIUmwIz4BMjPCb+0Yqnn+Zuk+hoJQtcXdj+q4lEvvbOvTKm7aHVE2TdL62kXB6WVvc1Tk2jSFg1yO7ljvsbZuFq+b24VyOR6h8cXyUBpeoptlmpVk/Q3rbDltuE+PinOXgVQVKkjKBrKx9j1tl8MZrMOsCEgxYNNmi0ycJqfa3NSPunYsocld/xo39OVAZ7ophZi3dwpBIHOmqHbI+6hf90H/FHcMhERL5OnURX/t+GX4+LOl1/R0U6uQIDAQAB',//用不着
            'charset'=>'UTF-8',
            'MaxQueryRetry'=>"5",
            'QueryDuration'=>'5',
            'notify_url'=>'http://mww5.xuanwumobile.com/shop/Index/huidiao'
        );
        $qrPay = new \AlipayTradeService($alipay_config);
        $qrPayResult = $qrPay->qrPay($qrPayRequestBuilder);
        if ($qrPayResult->getTradeStatus() == 'SUCCESS'){
            $response = $qrPayResult->getResponse();
            $qrcode = $response->qr_code;
            return array('status'=>200,'msg'=>$qrcode);
        }else{
            return array('status'=>0,'msg'=>'失败');
        }
    }
    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParamOrder($no,$money){
//    public function getParam(){
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest',EXTEND_PATH);
//        $no = '5851546514677777712121212';
//        $no = time().rand(1000000,9999999);
//        $money = '0.01';
        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
            $aop->appId = "2018090761306686";
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"红集\","
                . "\"subject\": \"红集商品购买\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://mww5.xuanwumobile.com/shop/Order/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msgsss'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        }catch (\Exception $e){
            $res['msgsss'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }
    /**
     *支付宝的原路退款接口(商户处理用户的订单)
     */
    public function refund($payInfo){
        //仨参数：money,number
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeRefundRequest',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2018090761306686';
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->alipayrsaPublicKey=$this->config['ali_public'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeRefundRequest;
//        $refundAmount = $payInfo['money'];
        $refundAmount = 0.01;
        $request->setBizContent("{" .
            "\"out_trade_no\":\"".$payInfo['number']."\"," .
            "\"trade_no\":\"\"," .
            "\"refund_amount\":".$refundAmount."," .
            "\"refund_reason\":\"退款\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode) && $resultCode == 10000){
            return array('status'=>200,'msg'=>'操作成功');
        }else{
            return array('status'=>0,'msg'=>'调用接口失败');
        }
    }

    /**
     *支付宝和微信的原路退款接口：后台给商户的订单退款(还没用到)
     */
    public function refundAdmin($so_id){
        //仨参数：so_id,money,number
        $payInfo = Db::table('up_shop_order')->where('so_id', $so_id)
            ->field('so_id,so_money money,so_number number,so_back_transaction_id transaction_id,so_in_out,so_type')
            ->find();
        if($payInfo['so_in_out'] == 3){
            return array(['status'=>0,'msg'=>'请勿重复操作']);
        }
        if($payInfo['so_type'] == 1){
            $back = $this->refund($payInfo);
        }else{
            $back = $this->refundWxShop($payInfo);
        }
        if($back['status'] != 200){
            return array('status' => 0, 'msg' => '退款失败');
        }else {
            Db::startTrans();
            try {
                $order = Db::table('up_shop_order')->where('so_id', $payInfo['so_id'])->find();
                //1、改状态
                Db::table('up_shop_order')
                    ->where('so_id', $payInfo['so_id'])
                    ->update(['so_in_out' => 3]);
                //2、商户改积分
                $jifen = Db::table('up_shops')->where('s_id', $order['so_shop_id'])->value('s_integral');
                $jifen -= $order['so_jifen'];
                $update = array();
                $update['s_integral'] = $jifen;
                //不用考虑大于0的情况，因为是退款
                if ($jifen <= 0) {
                    $update['s_status'] = 2;
                }
                Db::table('up_shops')
                    ->where('s_id', $order['so_shop_id'])
                    ->update($update);
                Db::commit();
                return array('status' => 200, 'msg' => '操作成功');
            } catch (\Exception $e) {
                Db::rollback();
                return array('status' => 0, 'msg' => '状态更改失败');
            }
        }
    }
    public function checkReturn(){
        import('alipay.aop.AopClient',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag){
            return $_POST;
        }else{
            return false;
        }
    }
    //-------------------------**********************微信支付***********************------------------------------------
    //-------------------------**********************微信支付***********************------------------------------------
    //-------------------------**********************微信支付***********************------------------------------------
    //-------------------------**********************微信支付***********************------------------------------------

    public function WeChatPayReady($order,$type=false,$qr=false){
        // 获取配置项
        $weixinpay_config2=$this->config2;
        $config2 = array(
            'appid'=>$weixinpay_config2['APPID'],
            'mch_id'=>$weixinpay_config2['MCHID'],
            'nonce_str'=>'test',
            'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
            'notify_url'=>$weixinpay_config2['NOTIFY_URL']
        );
        if($type){
            $config2['notify_url']=$type;
        }
        // 合并配置数据和订单数据
        $data=array_merge($order,$config2);

        // 生成签名
        $sign=$this->makeSign($data);
        $data['sign']=$sign;
        $xml=$this->toXml($data);
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';//接收xml数据的文件
        $header[] = "Content-type: text/xml";//定义content-type为xml,注意是数组
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        curl_close($ch);
        $result=$this->toArray($response);
        if($result['return_code'] == 'FAIL'){
            $returnerr['msg'] = $result['return_msg'];
            $returnerr['type'] = 'error';
            return $returnerr;
        }else{
            $result['sign']=$sign;
            $result['nonce_str']='test';
            if($qr == true){
                return $result;///
            }else{
                $result2 = $this->getOrder($result['prepay_id']);
                return $result2;///
            }

        }

    }
    /**
     * 获取时间
     * @return array
     */
    public function getDateBytimeDate($string){
        $replacement = '-';
        $replacement2 = ':';
        $a = substr_replace($string, $replacement, 4, 0);
        $b = substr_replace($a, $replacement, 7, 0);
        $c = substr_replace($b, ' ', 10, 0);
        $d = substr_replace($c, $replacement2, 13, 0);
        $e = substr_replace($d, $replacement2, 16, 0);
        return $e;
    }


    /**
     * 输出xml字符
     * @throws WxPayException
     **/
    public function toXml($data){
        //var_dump($data);
        if(!is_array($data) || count($data) <= 0){
            //throw new WxPayException("数组数据异常！");
        }
        $xml = "<xml>";
        foreach ($data as $key=>$val){
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    /**
     * 生成签名
     * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
     */
    public function makeSign($data){
        // 去空
        $data=array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a=http_build_query($data);
        $string_a=urldecode($string_a);
        //签名步骤二：在string后加入KEY
        $config2=$this->config2;
        $string_sign_temp=$string_a."&key=".$config2['KEY'];
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result=strtoupper($sign);
        return $result;
    }

    /**
     * 将xml转为array
     * @param  string $xml xml字符串
     * @return array       转换得到的数组
     */
    public function toArray($xml){
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }
    //获取指定长度的随机字符串
    function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }
    //执行第二次签名，才能返回给客户端使用
    public function getOrder($prepayId){
        $data["appid"] = $this->config2["APPID"];
        $data["noncestr"] = $this->getRandChar(32);
        $data["package"] = "Sign=WXPay";
        $data["partnerid"] = $this->config2['MCHID'];
        $data["prepayid"] = $prepayId;
        $data["timestamp"] = time();
        $s = $this->makeSign($data);
        $data["sign"] = $s;
        return $data;
    }

    /**
     * app支付统一退款
     */
    public function refundWx($payInfo,$refundNo=''){
        $refundNo = date('YmdHis') . rand(100000, 999999);
        //transaction_id,money,number
//    public function refundWx(){
        header("content-type:text/html;charset=utf-8");
        $url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
        $data["appid"] 		  = 'wxa15f6b72c349863c';//微信开放平台审核通过的应用APPID
        $data["mch_id"] 	  = '1515729741';//商户号
        $data["nonce_str"] 	  = $this->getRandChar(32);//随机字符串
        $data["out_refund_no"]   = $refundNo;
//        $data["refund_fee"] = $payInfo['money']*100;
        $data["refund_fee"] = 1;//todo 测试阶段全部按一分进行计算
        $data["total_fee"]  = $data['refund_fee'];//总金额按乘以100进行计算
        $data["transaction_id"]   = $payInfo['transaction_id'];//微信官方唯一订单识别号
        $data["out_trade_no"] = $payInfo['number'];
        $data["refund_fee_type"] = "CNY";
        $data["refund_account"] = "REFUND_SOURCE_UNSETTLED_FUNDS";
        $sign=$this->getSignRefund($data,'SzXuQnPCQAL4JnQWCoXxzWmlbTmJOiSm');
        $data['sign']=$sign;
        $xml=$this->toXml($data);
        $response 	= $this->postXmlCurl($xml, $url,'',true,'/cert/apiclient_cert.pem','/cert/apiclient_key.pem');
        $responseArr=$this->toArray($response);
        if(!is_array($responseArr) || count($responseArr)<=0){
            $return['msg'] = '网络请求繁忙';
            $return['status'] = 0;
        }else if($responseArr['return_code'] == 'FAIL'){
            $return['msg'] = $responseArr['return_msg'];
            $return['status'] = 0;
        }else{
            //二次签名
            $return['text'] = $responseArr;
//			直接返回
            $return['status'] = 200;
        }
        return $return;
    }
    /**
     * app支付统一退款(为商户的支付退款)
     */
    public function refundWxShop($payInfo,$refundNo=''){
        $refundNo = date('YmdHis') . rand(100000, 999999);
        //transaction_id,money,number
//    public function refundWx(){
        header("content-type:text/html;charset=utf-8");
        $url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
        $data["appid"] 		  = $this->config2['APPID'];//微信开放平台审核通过的应用APPID
        $data["mch_id"] 	  = $this->config2['MCHID'];//商户号
        $data["nonce_str"] 	  = $this->getRandChar(32);//随机字符串
        $data["out_refund_no"]   = $refundNo;
//        $data["refund_fee"] = $payInfo['money']*100;
        $data["refund_fee"] = 1;//todo 测试阶段全部按一分进行计算
        $data["total_fee"]  = $data['refund_fee'];//总金额按乘以100进行计算
        $data["transaction_id"]   = $payInfo['transaction_id'];//微信官方唯一订单识别号
        $data["out_trade_no"] = $payInfo['number'];
        $data["refund_fee_type"] = "CNY";
        $data["refund_account"] = "REFUND_SOURCE_UNSETTLED_FUNDS";
        $sign=$this->getSignRefund($data,$this->config2['KEY']);
        $data['sign']=$sign;
        $xml=$this->toXml($data);
        $response 	= $this->postXmlCurl($xml, $url,'',true,'/shopcert/apiclient_cert.pem','/shopcert/apiclient_key.pem');
        $responseArr=$this->toArray($response);
        if(!is_array($responseArr) || count($responseArr)<=0){
            $return['msg'] = '网络请求繁忙';
            $return['status'] = 0;
        }else if($responseArr['return_code'] == 'FAIL'){
            $return['msg'] = $responseArr['return_msg'];
            $return['status'] = 0;
        }else{
            //二次签名
            $return['text'] = $responseArr;
//			直接返回
            $return['status'] = 200;
        }
        return $return;
    }
    function getSignRefund($obj, $api_key)
    {
        foreach ($obj as $k => $v)
        {
            $Parameters[strtolower($k)] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);

        //签名步骤二：在string后加入KEY
        $String = $String."&key=".$api_key;
        //签名步骤三：MD5加密
        $result = strtoupper(md5($String));
//        $result = hash_hmac("sha256",stringSignTemp,key);
        return $result;
    }

    function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
                $v = urlencode($v);
            }
            $buff .= strtolower($k) . "=" . $v . "&";
        }
        $reqPar = '';
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }
    function postXmlCurl($xml, $url, $second=30, $useCert=false, $sslcert_path, $sslkey_path)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch,CURLOPT_URL, $url);

        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);

        if($useCert == true){
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
//            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
//			curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);//严格校验
            //设置证书
            $path = $_SERVER['DOCUMENT_ROOT'];
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLCERT, $path.$sslcert_path);
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLKEY, $path.$sslkey_path);
//            curl_setopt($ch,CURLOPT_CAINFO, __DIR__.'/cert/rootca.pem');
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            return false;
        }
    }
}